from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.db import models

class Category(models.Model):
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now=False)
    updated_at = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=45)
    slug = models.SlugField(db_index=True, unique=True, max_length=45)
    brief_description = models.TextField(null=True, blank=True)
    
    def services(self):
        return Service.objects.all().filter(active = True, category__id = self.id, ).order_by('name')
    
    def __unicode__(self):
        return str(self.name)

class Service(models.Model):
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now=False)
    updated_at = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=45)
    slug = models.SlugField(db_index=True, unique=True, max_length=45)
    category = models.ForeignKey(Category)
    brief_description = models.TextField(null=True, blank=True)
    before_image = models.FileField(upload_to = 'uploads/img/', null=True, blank=True)
    after_image = models.FileField(upload_to = 'uploads/img/', null=True, blank=True)
    
    @property
    def description(self):
        if self.brief_description:
            return self.brief_description
        else:
            if self.category.brief_description:
                return self.category.brief_description
        return 'Description coming soon.'
        
#        if not self.brief_description:
#            if self.category__brief_description:
#                return self.category__brief_description
#            else:
#                return 'Description coming soon'
#        else:
#            return self.brief_description

    @property
    def hero_image(self):
        img = ''
        try:
             img = ServiceImage.objects.filter(service = self, hero_image = True)[0].image
        except:
            pass
        
        return img
    
    @models.permalink
    def get_absolute_url(self):
        return ('service', (), {'slug_service': self.slug})

    def __unicode__(self):
        return str(self.name)

class ServiceImage(models.Model):
    image = models.FileField(upload_to='uploads/img/')
    alt = models.CharField(max_length=45, null=True, blank=True)
    service = models.ForeignKey(Service, related_name='service_image_service')
    hero_image = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.image)
